package com.bss.dao;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.andy.basics.Dao;
import com.bss.model.Admission;

@Repository
public class AdmissionDao extends Dao<Admission> {

	/**
	 * Find all admission for this patient first name
	 * 
	 * @param name
	 * @return
	 */
	public List<Admission> findForPatientName(final String name) {
		List<Admission> list = this.findComplex("Select adm from " + Admission.class.getName() + " as adm "
				+ "join adm.patient as pat where pat.firstName like '" + name + "%' order by pat.firstName asc");
		return list;
	}

	/**
	 * Find all admission which are active - all deposits are done for this
	 * admissions
	 * 
	 * @param name
	 * @return
	 */
	public List<Admission> findActiveAdmissios(final String name) {
		List<Admission> list = this.findComplex("Select adm from " + Admission.class.getName() + " as adm "
				+ "join adm.patient as pat where adm.active = true and adm.exitInited = false and pat.firstName like '" + name
				+ "%' order by pat.firstName asc");
		return list;
	}

	/**
	 * Find all admission even if not active. Relevant for payments after fresh
	 * admission
	 * 
	 * @param name
	 * @return
	 */
	public List<Admission> findCurrentAdmissions(final String name) {
		List<Admission> list = this.findComplex("Select adm from " + Admission.class.getName() + " as adm "
				+ "join adm.patient as pat where adm.dateOfExit is null and pat.firstName like '" + name
				+ "%' order by pat.firstName asc");
		return list;
	}

	public List<Admission> findExitsForDate(final Date date) {

		Calendar base = Calendar.getInstance();
		base.setTime(date);

		Calendar start = new GregorianCalendar(base.get(Calendar.YEAR), base.get(Calendar.MONTH), base.get(Calendar.DAY_OF_MONTH),
				0, 0);
		Calendar end = new GregorianCalendar(base.get(Calendar.YEAR), base.get(Calendar.MONTH), base.get(Calendar.DAY_OF_MONTH),
				23, 59);

		Query q = this.getEntityManager().createQuery(
				"select a from com.bss.model.Admission a where a.dateOfExit >= ? and a.dateOfExit <= ?");

		q.setParameter(1, start.getTime());
		q.setParameter(2, end.getTime());

		List<Admission> list = q.getResultList();
		return list;
	}

	public List<Admission> findExitsAfter(final Date date) {

		Query q = this.getEntityManager().createQuery("select a from com.bss.model.Admission a where a.dateOfExit >= ?");
		q.setParameter(1, date);
		List<Admission> list = q.getResultList();

		return list;
	}

	public Admission findLastAdmission(Integer patientId) {
		List<Admission> a = this.find("patient.id=" + patientId + " order by dateOfExit desc ");
		return a.get(0);
	}

}
